extends Control
# This Script Manage filement scale inside the slot
class_name Slot
@onready var BGRect: TextureRect = $BG
@onready var item_icon: Button = $ItemIcon
@onready var UpdateTimer: Timer = $UpdateTimer
@onready var NameLabel: Label =  $ItemIcon/NameLabel
var bag_name: String
var item_info_tscn=preload("res://scenes/stages/player_bag_and_info/other_scene/item_info.tscn")#详细信息
var item_operate_tscn=preload("res://scenes/stages/player_bag_and_info/other_scene/item_operate.tscn")#右键出现的列表栏
@export var item_info_dict: Dictionary = {}
@export var item_icon_path_key: String = "icon"
@export var mouse_slot: MouseSlot
@export var DefaultIcon: Resource = load("res://icon.svg")

var item_pandora: PandoraEntity
var index:int = 0
var bag_tscn
var MouseInSlot:bool=false
var ui
func _ready():
	# 初始化UI大小
	# BGRect.size = custom_minimum_size
	ui = get_tree().get_first_node_in_group("ui")
	set_deferred("custom_minimum_size",BGRect.size)
	item_icon.custom_minimum_size = BGRect.get_size() - Vector2(15,15)
	item_icon.expand_icon = true
	#item_icon.pressed.connect(_on_Icon_Clicked)
	#item_icon.button_down.connect(_on_Icon_Clicked)
	pivot_offset = size/2
	initTimer()

func initTimer():
	# setUp UpdateTimer
	UpdateTimer.wait_time = 0.1
	UpdateTimer.timeout.connect(OnUpdateTimer_Timeout)
	UpdateTimer.start()

	
func OnUpdateTimer_Timeout():
	# update Item info to slotUI
	# 更新图标和数量
	update_item_info_dict()
	#print("Slot Updated bv Timer")


func update_item_info_dict():
	if item_info_dict :
		if item_info_dict.has("name"):
			NameLabel.text = str(item_info_dict["name"])
		if item_info_dict.has(item_icon_path_key):
			item_icon.icon = load(item_info_dict[item_icon_path_key])
		else:
			# 对于没有定义icon的物品，加载默认的ICON
			item_icon.icon = DefaultIcon
	else:
		# 空格子的显示方式
		NameLabel.text = ""
		item_icon.icon = null

func swap_item_with_mouse_slot(is_back: bool = false):
	if mouse_slot:
		var temp_dic: Dictionary = {}
		var temp_pandora = null
		## 如果mouse_slot没有装备，先移走当前格子的装备
		if mouse_slot.item_info_dict.is_empty():
			mouse_slot.item_info_dict = self.item_info_dict#移走的格子
			mouse_slot.item_pandora = self.item_pandora
			self.item_info_dict = temp_dic
			self.item_pandora = temp_pandora
			mouse_slot.last_slot = self
			update_item_info_dict()
			return 	
		
		if not mouse_slot.item_info_dict.has("type"):
			update_item_info_dict()
			return
		
		## 先存储mouse_slot上的资料
		temp_dic = mouse_slot.item_info_dict.duplicate() #选中的格子
		temp_pandora = mouse_slot.item_pandora.duplicate() #选中的格子
		
		var last_slot = mouse_slot.last_slot
		if last_slot and not is_back:
			last_slot.item_info_dict = self.item_info_dict
			last_slot.item_pandora = self.item_pandora
			last_slot.update_item_info_dict()
			if last_slot is Equipment_Slot and last_slot.item_pandora:
				Utils.add_to_player(last_slot.item_pandora)
				
		self.item_info_dict = temp_dic
		self.item_pandora = temp_pandora
		
		mouse_slot.last_slot = null	
		mouse_slot.clear_mouse_slot()
	else:
		print("mouse_slot NULL")
	update_item_info_dict()

func CheckDragging():
	if MouseInSlot and Input.is_action_pressed("MouseLeft"):
		swap_item_with_mouse_slot()
		position = get_global_mouse_position()-(size/2)
		print("draging")

func _on_Icon_Clicked():
	# 直接用按钮判断鼠标点击
	swap_item_with_mouse_slot()
	pass
	
var item_info
func show_item_info():
	if item_info_dict and item_info==null:
		var attribute = item_info_tscn.instantiate()
		item_info = attribute
		
		ui.add_child(attribute)
		attribute.global_position = global_position + size/1.3
		attribute.z_index = z_index+1
		attribute.top_level = true
		attribute.get_node("BoxContainer/Panel/name").set_text(item_info_dict["name"])
		attribute.get_node("BoxContainer/info/info").set_text(ItemManager.get_item_info(item_pandora))
		#attribute.size.y = (28 + attribute.get_node("BoxContainer").get_child_count() * 28)
		
func show_item_Operate():
	hidden_item_info()
	var Operate = item_operate_tscn.instantiate()
	ui.add_child(Operate)
	Operate.show_ItemOperate(self)
	Operate.global_position = global_position + size/1.3
	Operate.z_index = z_index+1
	
func hidden_item_operate():
	if ui.has_node("ItemOperate"):
		ui.get_node("ItemOperate").queue_free()
		
func hidden_item_info():
	if item_info!=null:
		item_info.queue_free()
	
func _on_item_icon_mouse_entered():
	show_item_info()
	
func _on_item_icon_mouse_exited():
	hidden_item_info()

func use_item():#使用 
	item_info_dict.clear()
	update_item_info_dict()
	hidden_item_operate()
	
func queue_free_item():#丢弃
	item_info_dict.clear()
	update_item_info_dict()
	hidden_item_operate()
	
func equipped():#装备 
	var Equipment_bag=get_parent().get_parent().get_parent().get_parent().get_parent().find_child("Equipment_bag_demo")
	var tempdic:Dictionary={}
	for equip in Equipment_bag.Epuiment_array:
		if equip[1] == item_info_dict["type"]:
			tempdic=item_info_dict
			item_info_dict=equip[0].item_info_dict
			equip[0].item_info_dict=tempdic
			equip[0].Updateitem_info_dict()
			break
		update_item_info_dict()
	hidden_item_operate()
	
func unload():#卸下
	var item_bag = get_parent().get_parent().get_parent().find_child("BAG_demo")
	var tempdic: Dictionary = {}
	var Null_slot = item_bag.Find_null_slot()[0]
	tempdic = item_info_dict
	item_info_dict = Null_slot.item_info_dict
	Null_slot.item_info_dict=tempdic
	Null_slot.Updateitem_info_dict()
	update_item_info_dict()
	hidden_item_operate()

var item_operate:Array

func _on_item_icon_gui_input(_event):#判断是否 右键 然后来实例化 ItemOperate
	pass

func _get_drag_data(_at_position: Vector2) -> Variant:
	swap_item_with_mouse_slot()
	return mouse_slot
	
func _can_drop_data(_at_position: Vector2, _data: Variant) -> bool:
	return true

func _drop_data(_at_position: Vector2, _data: Variant) -> void:
	swap_item_with_mouse_slot()
